<template>
  <div>
    <layout @go="go" title="配置创意">
      <resTable :list="resList"></resTable>
    </layout>
    <a-modal v-model="show" okText="确定" @ok="ok" :width="650">
      <div class="content">
        <a-form-model ref="ruleForm" :model="bulkForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-model-item label="品牌名称" prop="brand">
            <a-input placeholder="请输入品牌名称, 最多11个字符" v-model="bulkForm.brand" :maxLength="11"/>
          </a-form-model-item>
          <a-form-model-item label="品牌头像" prop="userPortrait">
            <a-upload
              list-type="picture-card"
              :file-list="fileList"
              :beforeUpload="beforeUpload"
              @change="handleChange"
              @preview="handlePreview"
            >
              <div v-if="fileList.length == 0">
                <a-icon type="plus" />
                <div class="ant-upload-text"> 上传 </div>
              </div>
            </a-upload>
          </a-form-model-item>
          <a-form-model-item label="创意来源" prop="ideaType">
            <a-checkbox-group v-model="bulkForm.ideaType" @change="ontypeCheckChange">
              <a-row style="margin-top:9px;width: 200px;">
                <a-col :span="10">
                  <a-checkbox :value="1">程序化</a-checkbox>
                </a-col>
                <a-col :span="10">
                  <a-checkbox :value="3">自定义</a-checkbox>
                </a-col>
              </a-row>
            </a-checkbox-group> 
          </a-form-model-item>
          <a-form-model-item label="程序化" prop="program" v-if="bulkForm.ideaType.includes(1)">
            <div class="item" v-for="(item,index) in bulkForm.program" :key="index">
              <span>{{ item.title+'：' }} </span>
              <a-input-number v-model="item.value" type="number" :addon-before="item.title+':'" addon-after="个"  :min="0"  @change="(val)=>{item.value=val?val:0}" ref=""/>
            </div>
          </a-form-model-item>
          <a-form-model-item label="自定义" prop="custom" v-if="bulkForm.ideaType.includes(3)">
            <div class="item" v-for="(item,index) in bulkForm.custom" :key="index">
              <span>{{ item.title+'：' }} </span>
              <a-input-number v-model="item.value" type="number" :addon-before="item.title+':'" addon-after="个"  :min="0" @change="(val)=>{item.value=val?val:0}" />
            </div>
          </a-form-model-item>
          <a-form-model-item label="创意标题" prop="biaoti">
            <m-textline :values="bulkForm.biaoti" title="创意标题" @change="changeTextLine" />
            <chagptView :top="8" :left="80" :GptValue.sync="bulkForm.biaoti" />
          </a-form-model-item>
          <a-form-model-item label="商品描述" prop="describe">
            <m-textline :values="bulkForm.describe" title="商品描述" @change="changeDescribe" />
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import layout from '../layout'
import resTable from '../resTable'
import chagptView from '../chagptView'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

function dataURItoBlob(base64Data) {
    // 转Blob流
    // console.log(base64Data);//data:image/png;base64,
    var byteString;
    if(base64Data.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(base64Data.split(',')[1]);//base64 解码
    else{
        byteString = unescape(base64Data.split(',')[1]);
    }
    var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];//mime类型 -- image/png

    // var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
    // var ia = new Uint8Array(arrayBuffer);//创建视图
    var ia = new Uint8Array(byteString.length);//创建视图
    for(var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    var blob = new Blob([ia], {
        type: mimeString
    });
    return blob;
}

export default {
  props:{
    describe:{
      type:Array,
      default: () => []
    }
  },
  data() {
    let checkUserPortrait = (rule, value, callback) => {
      // console.log(rule, value, callback)
      if(value.blob == ''){
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }
    return {
      show: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      rules:{
        brand: [{required: true, message: '请输入品牌名称', trigger: 'blur' }],
        userPortrait: [{validator: checkUserPortrait, message: '请选择品牌头像', trigger: 'blur',required: true, }],
        biaoti: [{required: true, message: '请输入标题', trigger: 'blur' }],
        describe: [{required: true, message: '请输入描述', trigger: 'blur' }],
      },
      fileList:[],
      resList:[],
      previewVisible:false,
      previewImage:'',
      bulkForm:{
        brand:'',
        userPortrait:{name: '', blob: ''},  //品牌头像文件
        biaoti:[],
        describe:[],
        ideaType:[1],
        program:[
          {title:'标题',value:0,key:'title'},
          {title:'描述',value:0,key:'describe'},
          {title:'图片',value:0,key:'pic'},
          {title:'视频',value:0,key:'video'},
        ],
        custom:[
          {title:'图片',value:0,key:'pic'},
          {title:'视频',value:0,key:'video'},
        ],
      },
      copy_ideaType:[1],
    }
  },
  methods:{
    ok(){
      console.log(this.bulkForm)
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.resList = [
            {name:'品牌名称', value: this.bulkForm.brand},
            {name:'创意标题', value: this.bulkForm.biaoti.join('、')},
            {name:'商品描述', value: this.bulkForm.describe.join('、')},
            {name:'程序化', value: this.bulkForm.program.map(e=>e.title + e.value + '个').join('、')},
            {name:'自定义', value: this.bulkForm.custom.map(e=>e.title + e.value + '个').join('、')},
          ]
          this.show = false
          this.$emit("update:form", this.bulkForm)
        } 
      })
    },
    go(){
      this.show = true
    },
    changeTextLine(val){
      let biaoti = []
      for(let i of val){
        i = i.replace(/\s*/g,"")
        biaoti.push(i.slice(0,this.getStringLength(i, 60)))
      }
      this.bulkForm.biaoti = biaoti
    },
    changeDescribe(val){
      let describe = []
      for(let i of val){
        i = i.replace(/\s*/g,"")
        describe.push(i.slice(0,this.getStringLength(i, 80)))
      }
      this.bulkForm.describe = describe
    },
    async beforeUpload(file){
      // console.log(file)
      if(!(file.type === 'image/jpeg' || file.type === 'image/png')){
        this.$message.error('只能上传JPG/PNG文件')
        return Promise.reject()
      }
      let filePreview = await getBase64(file);
      let WHResult = await this.checkWH(filePreview)
      if(!WHResult){
        this.$message.error('请上传1:1且至少120*120尺寸的图片')
        return Promise.reject()
      }
      this.fileList = [{
        uid: file.uid,
        name: file.name,
        url:filePreview,
      }]
      this.bulkForm.userPortrait = {name: file.name,blob:dataURItoBlob(filePreview)}
      return Promise.reject()
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    checkWH(base64Data){
      // 判断图片宽高
      return new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = function() {
          // console.log(this.width, this.height)
          if (this.width == this.height && this.width >= 120) { // 上传图片的宽高与传递过来的限制宽高作比较，超过限制则调用失败回调
            resolve(true);
          } else {
            resolve(false);
          }
        };
        image.onerror = reject;
        image.src = base64Data;
      });
    },
    handleChange({ fileList }){
      console.log('handleChange', fileList)
      this.fileList = fileList
      if(fileList.length == 0){
        this.bulkForm.userPortrait = {name: '', blob: ''}
      }
    },
    getStringLength(str, max){
      let len = 0
      let idx = 0 // 截止下标位置
      for(let i = 0; i < str.length; i++){
        if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
          len += 2;
        } else {
          len++;
        }
        if(len > max){
          break;
        }else{
          idx ++
        }
      }
      // console.log(str, idx, len <= max ? len : max)
      return idx
    },
    ontypeCheckChange(e){
      if(e.length == 0){
        this.$message.error('必须选择一项')
        this.bulkForm.ideaType = JSON.parse(JSON.stringify(this.copy_ideaType))
      }
    },
  },
  watch:{
    show(val){
      if(val){
        setTimeout(() => {
          // console.log(this.bulkForm.describe, this.describe)
          let describe = JSON.parse(JSON.stringify(this.describe))
          if(this.bulkForm.describe.length == 0){
            this.bulkForm.describe = this.bulkForm.describe.concat(describe)
          }else{
            this.bulkForm.describe = JSON.parse(JSON.stringify(this.bulkForm.describe))
          }
          this.changeDescribe(this.bulkForm.describe)
        },0);
      }
    },
    describe(val){
      this.bulkForm.describe = val
    },
    'bulkForm.describe'(){
      if(this.bulkForm.brand != '' && !this.show){
        this.resList = [
          {name:'品牌名称', value: this.bulkForm.brand},
          {name:'创意标题', value: this.bulkForm.biaoti.join('、')},
          {name:'商品描述', value: this.bulkForm.describe.join('、')},
          {name:'程序化', value: this.bulkForm.program.map(e=>e.title + e.value + '个').join('、')},
          {name:'自定义', value: this.bulkForm.custom.map(e=>e.title + e.value + '个').join('、')},
        ]
        this.$emit("update:form", this.bulkForm)
      }
    }
  },
  components:{layout, resTable, chagptView},
}
</script>

<style lang="less" scoped>
.content{
  overflow-y: auto;
  overflow-x: hidden;
  height: 600px;
}
.item{
  width: 200px;
}
/deep/ .mui-textline-main-title, /deep/ .mui-textline .veui-textarea{
  width: 450px;
}
</style>
